package com.ruitu.health;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.support.view.NoScrollViewPager;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.health.fragment.Home2Fragment;
import com.ruitu.health.fragment.Home3Fragment;
import com.ruitu.health_1.ui.fragment.CategoryFragment;
import com.ruitu.health_1.ui.fragment.MineFragment;
import com.ruitu.health_1.ui.fragment.ShoppingCartFragment;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.service.StepService;
import com.ruitu.router_module.support.widget.BottomNavigationViewEx;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

public class HomeActivity extends BaseActivity {
    private BottomNavigationViewEx bnve;
    private NoScrollViewPager vp;

    private VpAdapter adapter;

    private boolean mBond;
    private Messenger serverMessenger;
    private MyConn conn;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_home;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bnve = findViewById(R.id.bnve);
        vp = findViewById(R.id.vp);

        vp.setOffscreenPageLimit(9);
        vp.setScanScroll(false);

        bnve.enableAnimation(false);
        bnve.enableShiftingMode(false);
        bnve.enableItemShiftingMode(false);

        bnve.setIconsMarginTop(SizeUtils.dp2px(10));
        bnve.setIconSize(23, 23);
        bnve.setTextSize(10);
        bnve.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                return true;
            }
        });

        adapter = new VpAdapter(getSupportFragmentManager());
        vp.setAdapter(adapter);
        bnve.setupWithViewPager(vp);

        vp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (position == 2) {// 点击首页购物车的时候,先判断登录情况
                    if (CommonUtils.isLoginToActivity(HomeActivity.this)) {

                    } else {
                        ToastUtils.showShort("请先登录");
                    }
                }
            }
        });
        conn = new MyConn();
        Intent intent = new Intent(this, StepService.class);
        startService(intent);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (null != intent) {
            boolean isCart = bundle.getBoolean("isCart", false);
            Logg.i("isCart = " + isCart);
            if (isCart) {
                setCurrVp(2);
            }
        }
    }

    class MyConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serverMessenger = new Messenger(service);
            Log.i("Mian", "服务连接成功");
            mBond = true;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serverMessenger = null;
            mBond = false;
            Logg.i("连接失败");
        }
    }

    private Messenger aMessenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                String step = (String) msg.getData().get("step");
                Logg.i("Msg: " + step);
            }
        }
    });

    @Override
    protected void onDestroy() {
        if (mBond) {
            unbindService(conn);
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!CommonUtils.isLogin() && vp.getCurrentItem() == 2) {// 处理未登录时,购物车页面的跳转逻辑
            vp.setCurrentItem(0);
        }
    }

    // 切换vp页面
    public void setCurrVp(int index) {
        vp.setCurrentItem(index, true);
    }

    private class VpAdapter extends FragmentPagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {// 首页
                return Home3Fragment.newInstance();
            } else if (position == 1) {// 分类
                return CategoryFragment.newInstance();
            } else if (position == 2) {// 购物车
                return ShoppingCartFragment.newInstance();
            } else if (position == 3) {// 我的
                return MineFragment.newInstance();
            }

            return Home2Fragment.newInstance();
        }

        @Override
        public int getCount() {
            return 4;
        }
    }

    private long waitTime = 2000;
    private long touchTime = 0;

    @Override
    public void onBackPressed() {
        if (null != vp && vp.getCurrentItem() == 0) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                ToastUtils.showShortSafe("再按一次退出程序");
                touchTime = currentTime;
            } else {
                Intent backHome = new Intent(Intent.ACTION_MAIN);//启动一个意图,回到桌面
                backHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                backHome.addCategory(Intent.CATEGORY_HOME);
                startActivity(backHome);
//                System.exit(0);
//                super.onBackPressed();
            }
        } else {
            vp.setCurrentItem(0);
        }
    }
}